package com.hhdys.service;

import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.CachingRealm;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hhdys.dao.RoleFuncAssMapper;
import com.hhdys.model.Account;
import com.hhdys.model.RoleFuncAss;
import com.hhdys.model.RoleFuncAssExample;
import com.hhdys.shiro.DefaultRealm;

@Service
@Transactional
public class RoleFuncAssServiceImpl implements RoleFuncAssService {
	@Autowired
	private RoleFuncAssMapper dao;
	@Autowired
	private AccountService accountService;
	@Autowired
	private DefaultRealm realm;

	/**
	 * @return the dao
	 */
	public RoleFuncAssMapper getDao() {
		return dao;
	}

	/**
	 * @param dao
	 *            the dao to set
	 */
	public void setDao(RoleFuncAssMapper dao) {
		this.dao = dao;
	}

	@Override
	public boolean addAss(int roleId, String funcs) {
		// 删除之前的权限
		RoleFuncAssExample example = new RoleFuncAssExample();
		RoleFuncAssExample.Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(roleId);
		dao.deleteByExample(example);
		// 添加新的权限
		String[] Strs = funcs.split(",");
		for (String str : Strs) {
			dao.insert(new RoleFuncAss(roleId, NumberUtils.toInt(str)));
		}
		// 清空权限缓存

		List<Account> accounts = accountService.getAccountsByRole(roleId);
		for (Account account : accounts) {
			SimplePrincipalCollection principals = new SimplePrincipalCollection();
			principals.add(account.getUsername(), realm.getName());
			realm.clearCachedAuthorizationInfo(principals);
		}
		return true;
	}

	@Override
	public List<RoleFuncAss> getAssByRoleId(int roleId) {
		RoleFuncAssExample example = new RoleFuncAssExample();
		RoleFuncAssExample.Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(roleId);
		return dao.selectByExample(example);
	}

	/**
	 * @return the accountService
	 */
	public AccountService getAccountService() {
		return accountService;
	}

	/**
	 * @param accountService
	 *            the accountService to set
	 */
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	/**
	 * @return the realm
	 */
	public DefaultRealm getRealm() {
		return realm;
	}

	/**
	 * @param realm
	 *            the realm to set
	 */
	public void setRealm(DefaultRealm realm) {
		this.realm = realm;
	}
}
